<?php

namespace app\admin\model\wms;

use app\admin\model\Admin;

use app\admin\model\xmwms\Category;
use think\Model;
use think\model\concern\SoftDelete;


/**
 * Products
 */
class Products extends Model
{
     // 表名
     protected $name = 'wms_products';

     // 自动写入时间戳字段
     protected $autoWriteTimestamp = true;

     use SoftDelete;

     // 设置软删除字段
     protected $deleteTime = 'deleted_at';





     public function getCategoryIdsAttr($value)
     {
//          if ($value === '' || $value === null) return [];
//          if (!is_array($value)) {
//              return explode(',', $value);
//          }
          return $value;
     }



     public function setCategoryIdsAttr($value): string
     {
          return is_array($value) ? implode(',', $value) : $value;
     }

    // 获取三级分类返回值
    public function getCategoryNamesAttr($value, $data){
        $categoryIdArr = $this->getCategoryIdsAttr($data['category_ids']);
        $category = Category::where('id', 'in',$categoryIdArr)->column('name');
        return implode('/', $category);
    }

     //关联sku表
     public function skus()
     {
          return $this->hasMany(Skus::class, 'product_id', 'id');
     }

     // 一对一关联admin表
     public function admin()
     {
          return $this->belongsTo(Admin::class, 'admin_id', 'id')->withField('id,username,nickname');
     }

     /**
      * 搜索器-搜索商品名称。商品编码
      */

     public function searchTitleAttr($query,$value,$data){
         if($value){
             return $query->where('title|sub_title','like','%'.$value.'%');
         }
     }

    /**
     * 搜索器-搜索商品编码
     */

    public function searchEanAttr($query,$value,$data){
        if($value){
            return $query->where('ean',$value);
        }
    }

    /**
     * 搜索器-搜索商品状态
     */

    public function searchStatusAttr($query,$value,$data){
        if(strlen($value) > 0){
            return $query->where('status',$value);
        }
    }



    /**
     * 搜索器:商品商品分类
     * @param $value
     * @param $data
     */
    public function searchCategoryAttr($query, $value, $data)
    {
        if ($value) {
            if (gettype($value) == 'array') {
                $like_arr = [];
                foreach ($value as $k => $v) {
                    $like_arr[] = $v;
                    $like_arr[] = $v . ',%';
                    $like_arr[] = '%,' . $v . ',%';
                    $like_arr[] = '%,' . $v;
                }
                $query->where("category_ids", "like", $like_arr, 'or');
            } else {
                $like_arr = [
                    $value ,
                    $value . ',%',
                    '%,' . $value . ',%',
                    '%,' . $value
                ];
                $query->where("category_ids", "like", $like_arr, 'or');
            }
        }
    }



}
